package com.jishucai.tomcat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpServerCodec;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qiaowang 2021/4/15
 */
public class TomcatServer {


    private Map<String, Object> registerMap;

    public TomcatServer(Map<String, Object> registerMap) {
        this.registerMap = registerMap;
    }

    public void start () throws InterruptedException {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup)
//                  Socket参数，服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝。默认值，Windows为200，其他为128。
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 底层TCP协议的心跳机制。Socket参数，连接保活，默认值为False。
                    // 启用该功能时，TCP会主动探测空闲连接的有效性。可以将此功能视为TCP的心跳机制，
                    // 需要注意的是：默认的心跳间隔是7200s即2小时。Netty默认关闭该功能。
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new TomcatServerHandler(registerMap));
                        }
                    });
            ChannelFuture fu = serverBootstrap.bind(8888).sync();
            System.out.println("tomcat端口号启动成功，端口好为" + 8888);
            fu.channel().closeFuture().sync();

        } finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }






}
